<?php
require_once('TVB/pms/pdes/model/info_general_information.php');

class MisInfoGeneralInfo
{
    private $mis_api;
    private $mis_info_general_information; 
    private $sync_data = array();
    private $mis_data = array();
    private $recover_sql = array();
    private $error;
    private $relation_old;
    private $relation = array(
        'type'      => 'info_general_information', 
        'mis_id'    => '', 
        'mis_eid'   => '', 
        'mis_pid'   => '', 
        'pdes_id'   => '', 
        'pdes_eid'  => '', 
        'pdes_pid'  => ''
    );
	private $new;
	private $link_list;
	private $change_logs=array();

    function __construct(array $mis_pdes)/*{{{*/
    {
        $this->relation = array_merge($this->relation, $mis_pdes);
        $this->relation['type'] = 'info_general_information';
        $this->relation_old = $this->relation;
        $this->mis_api = new MisApi();
    }/*}}}*/

    public function import($general_information)/*{{{*/
    {
		$this->new = FALSE;
		$this->link_list = array();
		$this->change_logs = array();

        foreach ($general_information as $mis_id) {
            $param = array(
                'co_code' => $this->relation['co_code'],
                'type'      => 'info_general_information',
                'mis_id'    => $mis_id
            );
            $relation = mis_pdes::getRelation($param);

            if (!empty($relation)) {
                $this->relation = $relation[0];
                $this->importStart($mis_id, $relation[0]['pdes_id']);
            } else {
				$this->new = TRUE;
                $this->relation = $this->relation_old;
                $this->relation['mis_id'] = $mis_id;
                $this->importStart($mis_id);
            }
        }

        if (!empty($this->error)) {
            return FALSE;
        } else {
            return TRUE;
        }
    }/*}}}*/

    #import one general info
    private function importStart($mis_id, $pdes_id='')/*{{{*/
    {
        $this->sync_data = $this->mis_data = $this->recover_sql = array();

        try {
            #mis data
            $this->loadMisData($mis_id);

            if ($pdes_id) {
                $this->importInfoGeneralInfo($pdes_id);
            } else {
                $this->importNewInfoGeneralInfo();
            }

            $this->misLog($this->relation['pdes_id'], TRUE);
        } catch (MISException $e) {
            if ($this->relation['pdes_id']) {
                $this->misLog($this->relation['pdes_id'], FALSE, $e->getMessage());
            }

            $this->error[] = $e->getMessage();
        }
    }/*}}}*/

    private function importInfoGeneralInfo($pdes_id)/*{{{*/
    {
        #pdes data
        $info_general_information = new info_general_information;
        $pdes_info_general_information = $info_general_information->get($pdes_id); 

        #mis data
        $sync_info_general_info = MisMapping::getMapping('info_general_information', $this->mis_info_general_information);
        unset($sync_info_general_info->created_by);

        $new_info_general_information = Model::diff(clone $pdes_info_general_information, $sync_info_general_info);
        $new_info_general_information->modified_at = date('Y-m-d H:i:s');
        $new_info_general_information->status = AC::STATUS_NEW; //bug 4181

		if ($this->new === TRUE) {
	        Model::$dbo['w']->save($new_info_general_information);

			# change_log
			$this->change_logs[] = array(
				'type'=>'info_general_information',
				'keys' => array('id' => $pdes_id),
				'is_active'=>1,
				'is_publish'=>0,
				'episode_id'=>array($new_info_general_information->episode_id)
			);
		}

        $this->sync_data['info_general_information'] = MisMapping::formatLogData('info_general_information', (array)$pdes_info_general_information);
        $this->mis_data['info_general_information'] = MisMapping::formatLogData('info_general_information', (array)$sync_info_general_info);
        #$this->recover_sql[] = MisMapping::getRecoverSql('info_general_information', $pdes_info_general_information);

		$this->link_list[] = sprintf(AC::$mis_view_url, 'info_general_information', $pdes_id);
    }/*}}}*/

    private function importNewInfoGeneralInfo()/*{{{*/
    {
        $episode = new episode;
        $episode_detail = $episode->get($this->relation['pdes_eid']);

        #mis data
        $sync_info_general_info = MisMapping::getMapping('info_general_information', $this->mis_info_general_information);
        $sync_info_general_info->episode_id = $this->relation['pdes_eid'];
        $sync_info_general_info->publish_datetime = $episode_detail->publish_datetime;
        $sync_info_general_info->expire_datetime = $episode_detail->expire_datetime;
        $sync_info_general_info->status = AC::STATUS_NEW;
        $sync_info_general_info->created_at = date('Y-m-d H:i:s');
        $sync_info_general_info->modified_at = date('Y-m-d H:i:s');
        
        #sync data
        $info_general_information = new info_general_information;
        $info_general_information->set($sync_info_general_info);
        $pdes_id =  Model::$dbo['w']->save($info_general_information);
        if (!$pdes_id) {
            throw new MISException("importNewInfoGeneralInfo failure.");
        }

        #update relation
        $this->relation['pdes_id'] = $pdes_id;
        $rs = mis_pdes::updateRelation($this->relation);
        if (!$rs) {
            throw new MISException("update relation failure.");
        }

        $this->mis_data['info_general_information'] = MisMapping::formatLogData('info_general_information', (array)$sync_info_general_info);

		# change_log
		$this->change_logs[] = array(
			'type'=>'info_general_information',
			'keys' => array('id' => $pdes_id),
			'is_active'=>1,
			'is_publish'=>0,
			'episode_id'=>array($new_info_general_information->episode_id)
		);
    }/*}}}*/

    private function misLog($pdes_id, $success, $message='')/*{{{*/
    {
        $this->mis_log = (object) array(
            'pdes_id'       => $pdes_id, 
            'type'          => 'info_general_information',
            'sync_data'     => $success ? json_encode($this->sync_data) : json_encode(array()), 
            'mis_data'      => $success ? json_encode($this->mis_data) : json_encode(array()), 
            'status'        => $success ? 1 : 0, 
            'message'       => $message, 
            #'recover_sql'   => $success ? json_encode($this->recover_sql) : json_encode(array()), 
            'modified_by'   => CommonUtils::get_user(),
            'modified_at'   => date('Y-m-d H:i:s'),
        );

        $rs = mis_log::update($this->mis_log);
        if (!$rs) {
            throw new MISException("update mis log failure.");
        }
    }/*}}}*/

    private function loadMisData($mis_id)/*{{{*/
    {
        $param = array('KEY_ID' => $mis_id);
        $this->mis_info_general_information = $this->mis_api->getDataByApi('getiGeneral_infoDetails', $param);
        if (empty($this->mis_info_general_information) || !is_object($this->mis_info_general_information)) {
            throw new MISException("Load mis info_general_information failure.");
        }
    }/*}}}*/

    public function getErrorMessage(){/*{{{*/
        return !empty($this->error) ? implode("\n", $this->error) : '';
    }/*}}}*/

	public function getLinkList()
	{
		return $this->link_list;
	}
	public function getChangeLogs(){
		return $this->change_logs;
	}
}
?>
